package org.idea.mq.framework.rocketmq.provider;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.idea.mq.framework.rocketmq.common.FastJsonSerializer;
import org.idea.mq.framework.rocketmq.common.MqMsgSerializer;

import java.util.List;
import java.util.Scanner;

/**
 * 将消息投递到指定的queue上
 *
 * @Author linhao
 * @Date created in 10:17 下午 2022/4/18
 */
public class SendMsgToQueueApplication {

    public static final String GROUP_NAME = "mq-framework-application-provider";
    public static final String NAME_SERVER = "localhost:9876";
    public static final Integer SEND_TIME_OUT = 1000;
    public static DefaultMQProducer defaultMQProducer = new DefaultMQProducer();
    public static MqMsgSerializer mqMsgSerializer = new FastJsonSerializer();

    public static void main(String[] args) throws MQClientException {
        defaultMQProducer.setNamesrvAddr(NAME_SERVER);
        defaultMQProducer.setProducerGroup(GROUP_NAME);
        defaultMQProducer.setSendMsgTimeout(SEND_TIME_OUT);
        defaultMQProducer.setVipChannelEnabled(false);
        defaultMQProducer.start();

        System.out.println("mq producer启动了");
        while (true){
            System.out.println("请输入你想发送的文本信息");
            Scanner scanner = new Scanner(System.in);
            String nextLine = scanner.nextLine();
            sendTopicToFirstQueue(nextLine);
        }
    }

    public static void sendTopicToFirstQueue(String msg){
        try {
            SendResult sendResult = defaultMQProducer.send(createMessage("queue-a-topic", "*", msg),
                    new AlwaysFirstQueue(),"");
            System.out.println(sendResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private static Message createMessage(String topic, String tag, Object t) {
        return new Message(topic,tag,mqMsgSerializer.serializer(t));
    }

}
